package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public boolean updateLocation(Long userId, Double longitude, Double latitude, String addrStr) {
        try {
            Query query = Query.query(Criteria.where("userId").is(userId));
            UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
            if (userLocation == null) {
                UserLocation location = new UserLocation();
                location.setUserId(userId)
                        .setUserId(userId)
                        .setAddress(addrStr)
                        .setCreated(System.currentTimeMillis())
                        .setUpdated(System.currentTimeMillis())
                        .setLastUpdated(System.currentTimeMillis())
                        .setLocation(new GeoJsonPoint(longitude, latitude));
                mongoTemplate.save(location);
            } else {
                Update update = Update.update("location", new GeoJsonPoint(longitude, latitude))
                        .set("updated", System.currentTimeMillis())
                        .set("lastUpdated", userLocation.getUpdated());
                mongoTemplate.updateFirst(query, update, UserLocation.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Long> queryNearUser(Long userId, Double distance) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        if (userLocation == null) {
            return null;
        }

        Query location = Query.query(Criteria.where("location")
                .withinSphere(
                        new Circle(userLocation.getLocation(),
                                new Distance(distance / 1000, Metrics.KILOMETERS))
                ));

        List<UserLocation> userLocationList = mongoTemplate.find(location, UserLocation.class);

        return CollUtil.getFieldValues(userLocationList, "userId", Long.class);
    }
}
